<template>
  <view class="chat-container">
    <!-- 弹幕组件 -->
    <Barrager
      v-if="currentBarrager"
      :barragerContent="currentBarrager ? currentBarrager.barragerContent : ''"
      :userAvatarURL="currentBarrager ? currentBarrager.userAvatarURL : ''"
      :userAvatarURL20="currentBarrager ? currentBarrager.userAvatarURL20 : ''"
      :barragerColor="
        currentBarrager
          ? currentBarrager.barragerColor
          : 'rgba(255,255,255,0.85)'
      "
      @finished="onBarragerFinished"
    />

    <!-- 顶部导航栏 -->
    <ChatHeader
      :connection-status="connectionStatus"
      :node-name="nodeName"
      :online-count="onlineCount"
      @back="goBack"
      @reconnect="manualReconnect"
      @toggle-user-list="toggleUserList"
    />

    <!-- 活跃度圆形组件 - 右上角悬浮 -->
    <view class="activity-circle-float">
      <ActivityCircle />
    </view>

    <!-- 在线用户列表弹窗 -->
    <UserList
      v-if="showUserList"
      :users="onlineUsers"
      @close="toggleUserList"
    />

    <!-- 消息列表区域 -->
    <MessageList
      ref="messageListRef"
      :messages="messages"
      :current-user="currentUser"
      :current-user-avatar="currentUserAvatar"
      :loading="loading"
      :has-more="hasMore"
      :page="page"
      :keyboard-height="keyboardHeight + panelHeight"
      @load-more="loadMoreMessages"
      @scroll-to-bottom="scrollToBottom"
      @at-user="atUser"
      @show-menu="showMessageMenu"
      @handle-bubble-tap="handleMessageBubbleTap"
      @navigate-to-user="navigateToUserDetail"
    />

    <!-- 底部输入区域 -->
    <InputArea
      v-if="isUserLoggedIn"
      v-model:content="messageContent"
      :current-topic="currentTopic"
      :is-disabled="connectionStatus !== 'connected'"
      :quote-data="quoteData"
      :keyboard-height="keyboardHeight"
      @send-message="sendMessage"
      @open-red-packet="openRedPacket"
      @open-tail="openTail"
      @cancel-quote="cancelQuote"
      @scroll-to-bottom="scrollToBottom"
      @panel-height-change="handlePanelHeightChange"
    />

    <!-- 悬浮音乐播放器 -->
    <MusicPlayer ref="musicPlayerRef" :initial-visible="showMusicPlayer" />

    <!-- 消息操作菜单 -->
    <MessageMenu
      :is-visible="isMessageMenuVisible"
      :menu-style="messageMenuStyle"
      :message="currentMessage"
      :current-user="currentUser"
      @close="closeMessageMenu"
      @copy="copyMessageContent"
      @quote="quoteMessage"
    />

    <!-- 图片预览模态框 -->
    <view class="image-preview-modal" v-if="showImagePreview">
      <view class="image-preview-mask" @tap.stop="closeImagePreview"></view>
      <ImageViewer
        :value="[{ url: previewImageUrl }]"
        :editable="false"
        :itemSize="0"
        @preview-close="closeImagePreview"
      />
    </view>
  </view>
</template>

<script setup>
import {
  ref,
  onMounted,
  onBeforeUnmount,
  onUnmounted,
  nextTick,
  computed,
} from "vue";
import { useChatWebSocket } from "@/services/ChatWebSocket.js";
import {
  showLoading,
  hideLoading,
  showError,
  showSuccess,
} from "@/utils/common.js";
import api, { isLoggedIn } from "@/api";
import ChatHeader from "@/components/chat/ChatHeader.vue";
import UserList from "@/components/chat/UserList.vue";
import MessageList from "@/components/chat/MessageList.vue";
import InputArea from "@/components/chat/InputArea.vue";
import MusicPlayer from "@/components/chat/MusicPlayer.vue";
import ActivityCircle from "@/components/chat/ActivityCircle.vue";
import MessageMenu from "@/components/chat/MessageMenu.vue";
import Barrager from "@/components/chat/Barrager.vue";
import ImageViewer from "@/components/ImageViewer.vue";
import { onShow, onHide } from "@dcloudio/uni-app";

// 导入新的工具模块
import {
  handleChatMessage,
  handleRevokeMessage,
  handleRedPacketStatus,
  handleRedPacketNotice,
  handleDiscussionChange,
  extractMessageContent,
  prepareQuoteData,
  handleSystemMessage,
} from "@/components/chat/MessageUtils.js";

import {
  handleRedPacketClick as handleRedPacketClickUtil,
  handleMessageBubbleTap as handleBubbleTapUtil,
  calculateMenuPosition,
} from "@/components/chat/BubbleHandler.js";

// 聊天WebSocket服务
const chatWebSocket = useChatWebSocket();

// 用户登录状态检查 - 使用计算属性确保实时更新
const isUserLoggedIn = computed(() => {
  // 直接调用API中的isLoggedIn函数检查当前登录状态
  const loginStatus = isLoggedIn();
  console.log("计算属性检查登录状态:", loginStatus);
  return loginStatus;
});

// 用户信息
const currentUser = ref("");
const currentUserAvatar = ref("https://file.fishpi.cn/default-avatar.png");

// 聊天消息相关
const messages = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const messageContent = ref("");

// 面板高度相关
const panelHeight = ref(0);

// 滚动相关状态
const shouldAutoScroll = ref(true);
const userScrolled = ref(false);
const hasNewMessage = ref(false);
const newMessageCount = ref(0);
const scrollTop = ref(0);

// 页面状态相关
const showUserList = ref(false);
const showMusicPlayer = ref(false);
const keyboardHeight = ref(0);

// 获取组件引用
const messageListRef = ref(null);
const musicPlayerRef = ref(null);

// WebSocket连接相关
const connectionStatus = ref("disconnected");
const nodeName = ref("");
const onlineCount = ref(0);
const onlineUsers = ref([]);
const currentTopic = ref("");

// 消息菜单相关
const isMessageMenuVisible = ref(false);
const messageMenuStyle = ref({});
const currentMessage = ref(null);

// 引用功能
const quoteData = ref(null);

// 弹幕相关状态
const currentBarrager = ref(null);

// 图片预览相关
const previewImageUrl = ref("");
const showImagePreview = ref(false);

// 检查是否是图片URL
const isImageUrl = (url) => {
  if (!url || typeof url !== "string") return false;

  // 检查是否为直接的图片URL
  const imageRegex = /\.(jpeg|jpg|gif|png|webp)(\?.*)?$/i;
  if (imageRegex.test(url)) return true;

  // 检查是否为间接的图片URL (带有域名的)
  const indirectImageRegex = /https?:\/\/.*\.(jpeg|jpg|gif|png|webp)(\?.*)?$/i;
  if (indirectImageRegex.test(url)) return true;

  return false;
};

// 打开图片预览
const openImagePreview = (url) => {
  previewImageUrl.value = url;
  showImagePreview.value = true;
};

// 关闭图片预览
const closeImagePreview = () => {
  showImagePreview.value = false;
};

// 查找消息中的图片URL
const findChatImage = (content) => {
  if (!content) return null;

  try {
    // 如果是JSON格式，尝试解析
    if (
      typeof content === "string" &&
      (content.startsWith("{") || content.startsWith("["))
    ) {
      try {
        const parsed = JSON.parse(content);
        if (parsed && parsed.content) {
          content = parsed.content;
        }
      } catch (e) {
        // 解析失败，保持原样
      }
    }

    // 检查是否包含图片标签
    const hasImage = /<img.*?src=["'](.*?)["'].*?>/i.test(content);
    if (hasImage) {
      // 提取图片URL
      const match = content.match(/<img.*?src=["'](.*?)["'].*?>/i);
      if (match && match[1]) {
        return match[1];
      }
    }

    // 检查内容本身是否为图片URL
    if (isImageUrl(content.trim())) {
      return content.trim();
    }

    return null;
  } catch (error) {
    console.error("查找图片出错:", error);
    return null;
  }
};

// 处理消息气泡点击
const handleMessageBubbleTap = (data) => {
  console.log(data.message);

  const refs = { musicPlayerRef };
  const handlers = {
    handleRedPacketClick: (redPacketId, redPacketType) =>
      handleRedPacketClickUtil(
        redPacketId,
        redPacketType,
        api.chat.getRedPacket,
        { showLoading, hideLoading, showError }
      ),
  };

  // 检查是否点击的是图片
  if (data && data.message && data.message.content) {
    const imageUrl = findChatImage(data.message.content);
    if (imageUrl) {
      console.log("检测到图片点击:", imageUrl);
      openImagePreview(imageUrl);
      return;
    }
  }

  // 处理其他类型的点击（如红包等）
  handleBubbleTapUtil(data, refs, handlers);
};

// 获取当前用户信息
const getCurrentUser = async () => {
  try {
    const res = await api.user.getCurrentUser();

    if (res.code === 0) {
      currentUser.value = res.data.userName;
      // 设置用户头像
      if (res.data.userAvatarURL) {
        currentUserAvatar.value = res.data.userAvatarURL;
      }
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
};

// 同步WebSocket状态到本地
const syncWebSocketState = () => {
  connectionStatus.value = chatWebSocket.connectionStatus.value;
  // 确保节点名称能够正确显示
  if (chatWebSocket.nodeName.value) {
    nodeName.value = chatWebSocket.nodeName.value;
    console.log("同步节点名称:", nodeName.value);
  }
  onlineCount.value = chatWebSocket.onlineCount.value;
  onlineUsers.value = chatWebSocket.onlineUsers.value;
  currentTopic.value = chatWebSocket.currentTopic.value;
};

// 设置WebSocket事件处理程序
const setupWebSocketHandlers = () => {
  console.log("开始设置WebSocket事件处理程序");

  // 监听连接状态变化
  chatWebSocket.on("statusChange", (status) => {
    console.log("收到状态变化事件:", status);
    connectionStatus.value = status;

    // 连接成功后加载消息
    if (status === "connected") {
      console.log("WebSocket连接已建立，开始加载历史消息");
      loadMessages(true);
    }
  });

  // 监听聊天消息
  chatWebSocket.on("message", (data) => {
    console.log("收到聊天消息事件:", data);
    messages.value = handleChatMessage(data, messages.value);

    // 处理滚动
    if (shouldAutoScroll.value && !userScrolled.value) {
      nextTick(() => {
        scrollToBottom();
      });
    } else if (userScrolled.value) {
      // 用户正在查看历史，显示新消息提示
      hasNewMessage.value = true;
      newMessageCount.value++;
    }
  });

  // 监听弹幕消息
  chatWebSocket.on("barrager", (data) => {
    console.log("收到弹幕消息:", JSON.stringify(data));

    // 设置当前弹幕
    const barragerData = data.data || data;
    console.log("处理后的弹幕数据:", JSON.stringify(barragerData));

    // 检查必要的字段
    if (!barragerData.barragerContent) {
      console.error("弹幕内容为空:", barragerData);
      return;
    }

    // 简化弹幕数据，只保留内容和头像
    const completeData = {
      barragerContent: barragerData.barragerContent || "弹幕消息",
      userAvatarURL:
        barragerData.userAvatarURL ||
        "https://file.fishpi.cn/default-avatar.png",
      userAvatarURL20:
        barragerData.userAvatarURL20 ||
        barragerData.userAvatarURL ||
        "https://file.fishpi.cn/default-avatar.png",
      barragerColor: barragerData.barragerColor || "rgba(255,255,255,0.85)",
    };

    console.log("最终弹幕数据:", JSON.stringify(completeData));

    // 先设置弹幕数据
    currentBarrager.value = completeData;

    // 延时验证弹幕容器是否存在，确保DOM已更新
    setTimeout(() => {
      const query = uni.createSelectorQuery();
      query
        .select(".barrager-container")
        .boundingClientRect((data) => {
          if (!data) {
            console.log("弹幕DOM尚未渲染完成，这是正常的");
          } else {
            console.log("弹幕容器已渲染，位置:", data);
          }
        })
        .exec();
    }, 500);
  });

  // 监听msg类型消息（兼容旧格式）
  chatWebSocket.on("msg", (data) => {
    console.log("收到msg类型消息事件:", data);
    messages.value = handleChatMessage(data, messages.value);

    // 处理滚动
    if (shouldAutoScroll.value && !userScrolled.value) {
      nextTick(() => {
        scrollToBottom();
      });
    } else if (userScrolled.value) {
      // 用户正在查看历史，显示新消息提示
      hasNewMessage.value = true;
      newMessageCount.value++;
    }
  });

  // 监听在线用户信息
  chatWebSocket.on("online", (data) => {
    console.log("收到在线用户信息:", data);
    onlineCount.value = chatWebSocket.onlineCount.value;
    onlineUsers.value = chatWebSocket.onlineUsers.value;
    currentTopic.value = chatWebSocket.currentTopic.value;

    // 将在线用户数据保存到本地缓存，供其他页面使用（如专属红包）
    if (onlineUsers.value && onlineUsers.value.length > 0) {
      try {
        uni.setStorageSync(
          "chatOnlineUsers",
          JSON.stringify(onlineUsers.value)
        );
        console.log(
          "已将在线用户数据保存到缓存, 数量:",
          onlineUsers.value.length
        );
      } catch (e) {
        console.error("保存在线用户数据到缓存失败:", e);
      }
    }
  });

  // 监听消息撤回
  chatWebSocket.on("revoke", (data) => {
    console.log("收到消息撤回事件:", data);
    messages.value = handleRevokeMessage(data, messages.value);
  });

  // 监听系统消息
  chatWebSocket.on("systemMessage", (data) => {
    console.log("收到系统消息事件:", data);
    messages.value = handleSystemMessage(data, messages.value);

    // 处理滚动
    if (shouldAutoScroll.value && !userScrolled.value) {
      nextTick(() => {
        scrollToBottom();
      });
    }
  });

  // 监听红包状态
  chatWebSocket.on("redPacket", (data) => {
    console.log("[ChatWebSocket] 收到redPacket事件:", JSON.stringify(data));

    try {
      // 处理可能的数据格式差异
      const eventData = data.data || data;

      // 如果是红包领取通知（含有whoGot和whoGive字段）
      if (
        (eventData.type === "redPacketStatus" ||
          eventData.type === "redPacket") &&
        eventData.whoGot &&
        eventData.whoGive
      ) {
        console.log(
          "[ChatWebSocket] 检测到红包领取通知，交给handleRedPacketNotice处理"
        );

        // 记录处理前消息数量
        const beforeCount = messages.value.length;

        // 处理红包通知
        const updatedMessages = handleRedPacketNotice(
          eventData,
          messages.value
        );

        // 检查消息是否增加
        console.log(
          "[ChatWebSocket] 红包通知处理前消息数:",
          beforeCount,
          "处理后:",
          updatedMessages.length,
          "是否增加:",
          updatedMessages.length > beforeCount
        );

        // 如果消息数量没有增加，说明处理失败，尝试手动添加通知
        if (updatedMessages.length <= beforeCount) {
          console.warn("[ChatWebSocket] 红包通知没有被正确添加，尝试手动添加");

          // 手动创建一个系统通知消息
          const systemMessage = {
            oId: `redpacket_notice_manual_${
              eventData.oId || eventData.msgId || Date.now()
            }`,
            userAvatarURL: "https://file.fishpi.cn/favicon.png",
            userName: "系统",
            userNickname: "系统消息",
            time: new Date().toISOString(),
            content: `${eventData.whoGot} 领取了 ${eventData.whoGive} 发的红包`,
            _isSystemMsg: true,
            _isRedPacketNotice: true,
          };

          messages.value = [...messages.value, systemMessage];
          console.log("[ChatWebSocket] 手动添加红包通知完成");
        } else {
          // 正常更新消息
          messages.value = updatedMessages;
        }

        // 确保界面更新
        nextTick(() => {
          // 额外检查消息中是否包含通知
          const hasNotice = messages.value.some((m) => m._isRedPacketNotice);
          console.log(
            "[ChatWebSocket] 红包领取通知处理完成，消息数量:",
            messages.value.length,
            "含通知:",
            hasNotice
          );
        });
      } else {
        // 普通红包状态更新
        console.log(
          "[ChatWebSocket] 检测到红包状态更新，交给handleRedPacketStatus处理"
        );
        const oldLength = messages.value.length;
        messages.value = handleRedPacketStatus(eventData, messages.value);

        // 检查是否实际更新了消息
        nextTick(() => {
          console.log(
            "[ChatWebSocket] 红包状态更新处理完成，消息是否有变化:",
            oldLength !== messages.value.length || "未发生变化"
          );
        });
      }
    } catch (error) {
      console.error("[ChatWebSocket] 处理redPacket事件错误:", error);
    }
  });

  // 监听红包状态更新（兼容旧格式）
  chatWebSocket.on("redPacketStatus", (data) => {
    console.log(
      "[ChatWebSocket] 收到redPacketStatus事件:",
      JSON.stringify(data)
    );

    try {
      // 处理可能的数据格式差异
      const eventData = data.data || data;

      // 如果是红包领取通知（含有whoGot和whoGive字段）
      if (eventData.whoGot && eventData.whoGive) {
        console.log(
          "[ChatWebSocket] 检测到红包领取通知，交给handleRedPacketNotice处理"
        );

        // 记录处理前消息数量
        const beforeCount = messages.value.length;

        // 处理红包通知
        const updatedMessages = handleRedPacketNotice(
          eventData,
          messages.value
        );

        // 如果消息数量没有增加，说明处理失败，尝试手动添加通知
        if (updatedMessages.length <= beforeCount) {
          // 手动创建一个系统通知消息
          const systemMessage = {
            oId: `redpacket_notice_manual_${
              eventData.oId || eventData.msgId || Date.now()
            }`,
            userAvatarURL: "https://file.fishpi.cn/favicon.png",
            userName: "系统",
            userNickname: "系统消息",
            time: new Date().toISOString(),
            content: `${eventData.whoGot} 领取了 ${eventData.whoGive} 发的红包`,
            _isSystemMsg: true,
            _isRedPacketNotice: true,
          };

          messages.value = [...messages.value, systemMessage];
          console.log("[ChatWebSocket] 手动添加红包通知完成");
        } else {
          // 正常更新消息
          messages.value = updatedMessages;
        }

        // 确保界面更新
        nextTick(() => {
          // 额外检查消息中是否包含通知
          const hasNotice = messages.value.some((m) => m._isRedPacketNotice);
          console.log(
            "[ChatWebSocket] 红包领取通知处理完成，消息数量:",
            messages.value.length,
            "含通知:",
            hasNotice
          );
        });
      } else {
        // 普通红包状态更新处理保持不变
        console.log(
          "[ChatWebSocket] 检测到红包状态更新，交给handleRedPacketStatus处理"
        );
        const oldMessages = [...messages.value];
        messages.value = handleRedPacketStatus(eventData, messages.value);

        // 检查是否真的改变了状态
        nextTick(() => {
          // 检查是否有变化
          const hasChanged =
            JSON.stringify(oldMessages) !== JSON.stringify(messages.value);
          console.log(
            "[ChatWebSocket] 红包状态更新处理完成，消息是否有变化:",
            hasChanged
          );

          // 如果确实没有变化，手动触发强制更新
          if (!hasChanged && eventData.oId) {
            console.log(
              "[ChatWebSocket] 尝试强制刷新红包状态，红包ID:",
              eventData.oId
            );
            const msgIndex = messages.value.findIndex(
              (msg) => msg.oId === eventData.oId
            );

            if (msgIndex !== -1) {
              try {
                const targetMsg = messages.value[msgIndex];
                const content = JSON.parse(targetMsg.content);

                if (content.msgType === "redPacket") {
                  // 获取最新数据
                  const gotCount = eventData.got || 0;
                  const totalCount = content.totalCount || content.count || 0;
                  const leftCount = Math.max(0, totalCount - gotCount);
                  const isOver = leftCount === 0;

                  console.log("[ChatWebSocket] 强制更新红包状态:", {
                    leftCount: leftCount,
                    isOver: isOver,
                    从: gotCount,
                    共: totalCount,
                  });

                  // 强制更新
                  const updatedContent = JSON.stringify({
                    ...content,
                    leftCount: leftCount,
                    isOver: isOver,
                    _forceUpdate: Date.now(), // 添加时间戳强制更新
                  });

                  messages.value = [...messages.value];
                  messages.value[msgIndex] = {
                    ...targetMsg,
                    content: updatedContent,
                  };
                }
              } catch (e) {
                console.error("[ChatWebSocket] 强制更新红包状态失败:", e);
              }
            }
          }
        });
      }
    } catch (error) {
      console.error("[ChatWebSocket] 处理redPacketStatus事件错误:", error);
    }
  });

  // 监听讨论话题更改
  chatWebSocket.on("discussChanged", (data) => {
    console.log("收到讨论话题更改事件:", data);
    const result = handleDiscussionChange(data);
    currentTopic.value = result.topic;

    // 显示更改通知
    if (result.message) {
      uni.showToast({
        title: result.message,
        icon: "none",
        duration: 2000,
      });
    }
  });

  console.log("WebSocket事件处理程序设置完成");
};

// 加载历史聊天消息
const loadMessages = async (reset = false) => {
  if (loading.value) return;

  try {
    loading.value = true;

    if (reset) {
      page.value = 1;
      hasMore.value = true;
      // 清空现有消息，避免重复
      messages.value = [];
    }

    console.log("正在加载第", page.value, "页的消息");
    const res = await api.chat.getMessages(page.value);

    if (res.code === 0) {
      const newMessages = res.data || [];
      console.log(
        "获取到历史消息数量:",
        newMessages.length,
        "当前页码:",
        page.value
      );

      // 对消息进行排序，确保旧消息在上面，新消息在下面
      const sortedMessages = [...newMessages].sort((a, b) => {
        const timeA = new Date(a.time).getTime();
        const timeB = new Date(b.time).getTime();
        return timeA - timeB; // 按时间升序排列
      });

      if (reset) {
        messages.value = sortedMessages;
        // 只有在首次加载时才滚动到底部
        await nextTick();
        scrollToBottom();
      } else {
        // 加载更多历史消息时，将新消息添加到列表前面
        messages.value = [...sortedMessages, ...messages.value];
      }

      // 判断是否还有更多消息
      hasMore.value = newMessages.length >= 20;
      if (hasMore.value) {
        page.value++;
      }
    } else {
      console.error("加载消息失败:", res.msg);
      hasMore.value = false;
    }
  } catch (error) {
    console.error("加载聊天记录失败", error);
    hasMore.value = false;
  } finally {
    loading.value = false;
  }
};

// 加载更多消息
const loadMoreMessages = async () => {
  console.log("--------------------------------");
  console.log("加载更多消息被触发了！");
  console.log("hasMore:", hasMore.value, "loading:", loading.value);

  if (!hasMore.value || loading.value) {
    console.log("不满足加载条件，返回");
    return;
  }

  console.log("开始执行 loadMessages(false)");
  shouldAutoScroll.value = false;
  userScrolled.value = true;

  try {
    await loadMessages(false);
    console.log("loadMessages 执行完成");
  } catch (error) {
    console.error("加载更多消息出错:", error);
  }
  console.log("--------------------------------");
};

// 发送消息
const sendMessage = async (content) => {
  if (!content.trim()) return;

  try {
    // 处理引用
    if (quoteData.value) {
      const quote = quoteData.value;
      const quotePrefix = `\n\n ##### 引用 @${quote.userName} [↩](https://fishpi.cn/cr#chatroom${quote.oId} "跳转至原消息")\n\n> ${quote.content}\n\n`;
      content = content + quotePrefix;

      // 清除引用状态
      quoteData.value = null;
    }

    // 尝试添加小尾巴
    try {
      const tailSettings = uni.getStorageSync("chatTailSettings");
      if (tailSettings) {
        const settings = JSON.parse(tailSettings);
        if (settings.enableTail && settings.tailContent) {
          // 检查特殊指令，这些情况下不添加小尾巴
          const isModifyTopic = content.includes("[setdiscuss]");
          const isBarragerCmd = content.includes("[barrager]");
          const isGe = content.trim().startsWith("鸽 ");
          const isXiaoBingCmd = content.trim().startsWith("小冰 ");
          const isSongRequest = content.trim().startsWith("点歌 ");

          if (
            !isModifyTopic &&
            !isGe &&
            !isXiaoBingCmd &&
            !isSongRequest &&
            !isBarragerCmd
          ) {
            // 在消息末尾添加小尾巴
            content += `\n\n >${settings.tailContent}`;
          } else {
            console.log("检测到特殊指令，不添加小尾巴:", content);
          }
        }
      }
    } catch (e) {
      console.error("读取小尾巴设置失败", e);
    }

    // 发送消息前先清空输入框，提高响应感
    messageContent.value = "";

    // 使用WebSocket服务发送消息
    const result = await chatWebSocket.sendMessage(content);
    console.log("消息发送成功", result);

    // 滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  } catch (error) {
    console.error("发送消息失败:", error);
    showError(error.message || "发送消息失败");
  }
};

// 滚动到底部
const scrollToBottom = (delay = 100) => {
  // 只在特定情况下滚动到底部
  if (!userScrolled.value || shouldAutoScroll.value) {
    console.log("开始执行滚动到底部函数");
    setTimeout(() => {
      try {
        console.log("正在执行滚动到底部逻辑");
        const query = uni.createSelectorQuery();
        query.select(".chat-messages").boundingClientRect();
        query.select(".chat-list").boundingClientRect();

        query.exec((res) => {
          if (!res || !res[0] || !res[1]) {
            console.log("滚动查询结果无效:", res);
            scrollTop.value = 999999;
            return;
          }

          const containerHeight = res[0].height;
          const contentHeight = res[1].height;
          const newScrollTop = contentHeight - containerHeight + 100;

          console.log("滚动计算结果:", {
            containerHeight,
            contentHeight,
            newScrollTop,
          });

          if (newScrollTop > 0) {
            scrollTop.value = newScrollTop + 300;
            console.log("设置scrollTop为:", scrollTop.value);
          } else {
            scrollTop.value = 999999;
            console.log("设置scrollTop为最大值:", scrollTop.value);
          }

          // 额外检查消息列表引用是否存在
          if (messageListRef.value) {
            console.log("messageListRef存在，尝试直接调用其scrollToBottom方法");
            // 如果MessageList组件有暴露scrollToBottom方法，则直接调用
            if (typeof messageListRef.value.scrollToBottom === "function") {
              messageListRef.value.scrollToBottom();
            }
          }
        });
      } catch (error) {
        console.error("滚动尝试失败:", error);
        scrollTop.value = 999999;
      }
    }, delay);
  } else {
    console.log(
      "跳过滚动，因为 userScrolled=",
      userScrolled.value,
      "shouldAutoScroll=",
      shouldAutoScroll.value
    );
  }
};

// 切换用户列表显示
const toggleUserList = () => {
  showUserList.value = !showUserList.value;
};

// 手动重连
const manualReconnect = () => {
  chatWebSocket.manualReconnect();
};

// 显示消息菜单
const showMessageMenu = async (message) => {
  try {
    console.log("showMessageMenu被调用，消息:", message);

    // 确保消息包含必要的信息
    if (!message) {
      console.error("菜单显示失败: 消息对象为空");
      return;
    }

    // 先设置菜单为不可见，确保状态重置
    isMessageMenuVisible.value = false;

    // 等待一帧确保DOM更新
    await nextTick();

    const style = await calculateMenuPosition(message, currentUser.value);
    console.log("计算出的菜单样式:", style);

    if (style) {
      // 先设置样式和消息
      messageMenuStyle.value = style;
      currentMessage.value = message;

      // 等待一帧确保DOM更新
      await nextTick();

      // 然后再设置为可见
      isMessageMenuVisible.value = true;
      console.log("消息菜单已显示，状态:", isMessageMenuVisible.value);

      // 验证菜单是否显示
      setTimeout(() => {
        const query = uni.createSelectorQuery();
        query.select(".message-menu").boundingClientRect();
        query.exec((res) => {
          if (res && res[0]) {
            console.log("菜单元素已渲染，位置:", res[0].top, res[0].left);
          } else {
            console.error("菜单元素未找到! 尝试强制更新");
            // 强制更新
            isMessageMenuVisible.value = false;
            setTimeout(() => {
              isMessageMenuVisible.value = true;
            }, 50);
          }
        });
      }, 100);
    } else {
      console.error("菜单显示失败: 样式计算返回空");
      // 使用默认样式显示菜单
      messageMenuStyle.value = { top: "30%", left: "50%" };
      currentMessage.value = message;
      isMessageMenuVisible.value = true;
    }
  } catch (error) {
    console.error("显示消息菜单失败:", error);
    // 尝试使用默认样式显示菜单
    messageMenuStyle.value = { top: "30%", left: "40%" };
    currentMessage.value = message;
    isMessageMenuVisible.value = true;
  }
};

// 关闭消息菜单
const closeMessageMenu = () => {
  isMessageMenuVisible.value = false;
  currentMessage.value = null;
};

// 复制消息内容
const copyMessageContent = (message) => {
  if (!message || !message.content) return;

  try {
    // 使用工具函数提取内容
    const content = extractMessageContent(message);

    // 复制到剪贴板
    uni.setClipboardData({
      data: content,
      success: () => {
        uni.showToast({
          title: "复制成功",
          icon: "success",
        });
        closeMessageMenu();
      },
    });
  } catch (error) {
    console.error("复制消息内容失败", error);
    closeMessageMenu();
  }
};

// 引用消息
const quoteMessage = (message) => {
  if (!message) return;

  try {
    // 使用工具函数准备引用数据
    quoteData.value = prepareQuoteData(message);

    // 显示引用成功提示
    uni.showToast({
      title: `引用: @${quoteData.value.userName}`,
      icon: "none",
      duration: 2000,
    });

    // 关闭消息菜单
    closeMessageMenu();
  } catch (error) {
    console.error("引用消息失败", error);
    closeMessageMenu();
  }
};

// 取消引用
const cancelQuote = () => {
  quoteData.value = null;
};

// 长按用户头像@用户
const atUser = (message) => {
  if (!message || !message.userName) return;

  // 在输入框中添加@用户名
  messageContent.value += `@${message.userName} `;
};

// 导航到用户详情页
const navigateToUserDetail = (username) => {
  uni.navigateTo({
    url: `/pages/user/user-profile?username=${username}`,
  });
};

// 打开小尾巴设置页面
const openTail = () => {
  uni.navigateTo({
    url: "/pages/chat/tail-setting",
  });
};

// 打开红包功能
const openRedPacket = () => {
  uni.navigateTo({
    url: "/pages/chat/send-redpacket",
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 页面加载时初始化
onMounted(async () => {
  console.log("新版聊天页面已加载");

  console.log("登录状态检查:", isUserLoggedIn.value);

  // 监听自定义事件，用于处理从红包页面返回时重新注册事件处理器
  uni.$on("chat_page_need_refresh", (data) => {
    console.log("收到页面刷新事件:", data);
    // 重新注册事件处理器
    setupWebSocketHandlers();
    // 确保WebSocket连接正常
    if (chatWebSocket.connectionStatus.value === "disconnected") {
      chatWebSocket.initWebSocket();
    } else if (chatWebSocket.connectionStatus.value === "connected") {
      loadMessages(true);
    }
  });

  // 先同步一次全局状态，显示可能的已有节点名称
  syncWebSocketState();
  console.log("初始节点名称:", nodeName.value);
  console.log("当前WebSocket状态:", chatWebSocket.connectionStatus.value);

  if (isUserLoggedIn.value) {
    console.log("用户已登录，准备初始化聊天服务");

    // 获取当前用户信息
    await getCurrentUser();
    console.log("当前用户信息获取完成:", currentUser.value);

    // 总是先注册事件处理程序，确保接收消息的监听器就绪
    setupWebSocketHandlers();

    // 再次同步状态值，确保最新
    syncWebSocketState();

    // 检查WebSocket连接状态
    if (chatWebSocket.connectionStatus.value === "connected") {
      console.log("WebSocket已连接，不需要重新连接");
      // 已连接状态下，加载历史消息
      loadMessages(true);
    } else {
      // 未连接状态，初始化WebSocket连接
      console.log("WebSocket未连接，开始初始化连接");
      // 设置页面可见状态
      chatWebSocket.isPageVisible = true;
      chatWebSocket.initWebSocket();
    }
  } else {
    console.log("用户未登录，不初始化聊天服务");
  }

  // 监听键盘高度变化
  // #ifdef APP-PLUS
  uni.onKeyboardHeightChange((res) => {
    keyboardHeight.value = res.height;
  });
  // #endif
});

// 页面显示时执行
onShow(() => {
  console.log("聊天页面显示");
  console.log("onShow中检查登录状态:", isUserLoggedIn.value);

  // 强制更新DOM
  nextTick(() => {
    // 这里是空函数，仅用于触发DOM更新
  });

  if (isUserLoggedIn.value) {
    // 同步WebSocket状态
    syncWebSocketState();

    // 重新获取用户信息（可能在其他页面更新了头像等）
    getCurrentUser();

    // 如果WebSocket断开了连接，尝试重新连接
    if (chatWebSocket.connectionStatus.value === "disconnected") {
      console.log("检测到连接已断开，尝试重新连接");
      chatWebSocket.initWebSocket();
    }

    // 无论如何，都重新加载最新消息
    loadMessages(true);
  }
});

// 页面隐藏时执行
onHide(() => {
  console.log("聊天页面隐藏");

  // 检查当前页面是否是聊天页面
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const currentRoute = currentPage ? currentPage.route : "";

  // 如果当前页面不是聊天页面，彻底销毁WebSocket
  if (currentRoute !== "pages/chat/new-chat/index") {
    console.log("离开聊天页面，彻底销毁WebSocket");

    // 先取消所有事件注册
    if (chatWebSocket && typeof chatWebSocket.offAll === "function") {
      console.log("取消所有WebSocket事件注册");
      chatWebSocket.offAll();
    }

    if (
      chatWebSocket &&
      typeof chatWebSocket.destroyCompletely === "function"
    ) {
      chatWebSocket.destroyCompletely();
    }
  }
});

// 页面卸载时清理资源
onBeforeUnmount(() => {
  console.log("聊天页面即将卸载，清理资源");

  // 取消自定义事件监听
  uni.$off("chat_page_need_refresh");

  // 先取消所有事件注册
  if (chatWebSocket && typeof chatWebSocket.offAll === "function") {
    console.log("取消所有WebSocket事件注册");
    chatWebSocket.offAll();
  }

  // 设置页面为不可见状态，增加判断以确保isPageVisible是一个响应式对象
  if (
    chatWebSocket &&
    chatWebSocket.isPageVisible &&
    typeof chatWebSocket.isPageVisible === "object"
  ) {
    chatWebSocket.isPageVisible.value = false;
  }

  // 使用新的彻底销毁方法而不是普通的cleanup
  if (chatWebSocket && typeof chatWebSocket.destroyCompletely === "function") {
    chatWebSocket.destroyCompletely();
  }
});

onUnmounted(() => {
  // #ifdef APP-PLUS
  uni.offKeyboardHeightChange();
  // #endif
});

// 弹幕播放完成后处理
const onBarragerFinished = () => {
  console.log("弹幕播放完成");
  currentBarrager.value = null;
};

// 处理面板高度变化
const handlePanelHeightChange = (height) => {
  console.log("面板高度变化:", height, "原高度:", panelHeight.value);

  // 如果是从有高度变为0或从0变为有高度，使用一个短暂的延迟
  // 这样可以让UI有时间反应，避免突然的跳变
  if (
    (panelHeight.value > 0 && height === 0) ||
    (panelHeight.value === 0 && height > 0)
  ) {
    // 先设置为0，让界面有时间调整
    if (height === 0) {
      panelHeight.value = 0;
      // 滚动到底部
      nextTick(() => {
        scrollToBottom(0); // 立即滚动
      });
    } else {
      // 非0高度时，先设置一个过渡值，再设置最终值
      // 这种渐进式变化可以让滚动更平滑
      const transitionHeight = height / 2;
      panelHeight.value = transitionHeight;

      setTimeout(() => {
        panelHeight.value = height;
        // 延迟滚动到底部，等待界面调整完成
        scrollToBottom(50);
      }, 30);
    }
  } else {
    // 正常情况直接设置高度
    panelHeight.value = height;

    // 当面板高度变化时，确保滚动到底部
    nextTick(() => {
      scrollToBottom();
    });
  }
};
</script>

<style lang="scss" scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
  position: relative;
}

/* 未登录提示 */
.login-prompt {
  position: fixed;
  bottom: 100rpx;
  left: 0;
  right: 0;
  z-index: 100;
  padding: 30rpx;
  background-color: #fff;
  border-top: 1px solid rgba(0, 0, 0, 0.05);

  .login-content {
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f5f5;
    border-radius: 40rpx;
    color: #007aff;
    font-size: 28rpx;
  }
}

/* 活跃度圆形组件悬浮样式 */
.activity-circle-float {
  position: fixed;
  top: 180rpx;
  right: 25rpx;
  z-index: 101;
  transform-origin: center;
  opacity: 1;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.92);
  }
}

/* 图片预览模态框 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-preview-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999; /* 降低z-index值，使其低于ImageViewer中的控制按钮 */
}
</style>
